package org.lfh.wintersun.redis;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.Getter;
import org.lfh.wintersun.web.user.dao.SysUserDao;
import org.lfh.wintersun.web.user.entity.SysUserEntity;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class BloomFilterInitializer {

    @Resource
    private SysUserDao userMapper;

    @Getter
    private RBloomFilter<Long> userBloomFilter;

    @Resource
    private RedissonClient redissonClient;

    @PostConstruct
    public void init() {
        // 初始化布隆过滤器，预计插入 1000000 个元素，误判率为 0.01
        userBloomFilter = redissonClient.getBloomFilter("userBloomFilter");
        // 预计插入 1000000 个元素，误判率为 0.01
        userBloomFilter.tryInit(1000000L, 0.01);
        // 从数据库加载所有用户ID到布隆过滤器
        List<SysUserEntity> sysUserEntities = userMapper.selectList(new LambdaQueryWrapper<>());
        for (SysUserEntity user : sysUserEntities) {
            userBloomFilter.add(user.getId());
        }
    }

}